package com.tanhua.dubbo.api.impl;

import com.tanhua.domain.mongo.Sound;
import com.tanhua.dubbo.api.SoundApi;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@Service
public class SoundApiImpl implements SoundApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Sound sound) {
        mongoTemplate.save(sound);
    }

    @Override
    public List<Sound> findByUserId(Long id) {
        Query query = new Query(Criteria.where("userId").is(id));
        return mongoTemplate.find(query, Sound.class);
    }

    @Override
    public List<Sound> findAll() {
        Query query = new Query(Criteria.where("state").is(false));
        return mongoTemplate.find(query,Sound.class);
    }

    @Override
    public void clearSound() {
        Query query = new Query(Criteria.where("state").is(true));
        mongoTemplate.remove(query,Sound.class);
    }

    @Override
    public void updateState(Sound sound) {
        Query query = new Query(Criteria.where("_id").is(sound.getId()));
        Update update = new Update();
        update.set("state", true);
        mongoTemplate.updateFirst(query,update,Sound.class);
    }

    @Override
    public List<Sound> findByState() {
        Query query = new Query(Criteria.where("state").is(true));
        return mongoTemplate.find(query,Sound.class);
    }
}
